//
//  LFDBManager.swift
//  XiaoXiangMu1604
//
//  Created by qianfeng on 16/9/29.
//  Copyright © 2016年 SunPiaoLiang. All rights reserved.
//

import UIKit

/*
数据库
*/

class LFDBManager: NSObject {

    //数据库队列
    private var myQueue: FMDatabaseQueue?
    
    //获取单例对象的方法
    class var sharedManager: LFDBManager?{
        
        struct Static {
            
            static var onceToken: dispatch_once_t = 0
            
            static var instance: LFDBManager? = nil
            
        }
        
        dispatch_once(&Static.onceToken){
            
            Static.instance = LFDBManager()
            
        }
        
        return Static.instance!
        
    }
    
    override init() {
        
        //初始化数据库
        
        //文件路径
        let cacheDir = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).last
        
        let path = cacheDir?.stringByAppendingString("/collect.db")
        
        //创建队列
        myQueue = FMDatabaseQueue(path: path)
        
        
        //创建表格
        myQueue?.inDatabase({
            
            (database) in
            
            let createSql = "create table if not exists collect (collectId integer primary key autoincrement,applicationId varchar(255),name varchar(255),headImage blob)"
            
            let flag = database.executeUpdate(createSql, withArgumentsInArray: nil)
            
            if flag != true{
                
                print(database.lastErrorMessage())
                
            }
            
        })
        
    }
    
    func addCollect(model:CollectModel,finishClosure:(Bool->Void)){
        
        myQueue?.inDatabase({ (database)  in
            
            //插入语句
            let insertSql = "insert into collect (applicationId,name,headImage) values (?,?,?)"
            
            //图片转换成二进制的方法
            let data = UIImagePNGRepresentation(model.headImage!)
            
            let flag = database.executeUpdate(insertSql, withArgumentsInArray: [model.applicationId!,model.name!,data!])
            
            if flag != true{
                
                print(database.lastErrorMessage())
                
                
            }
          
            finishClosure(flag)
            
        })
        
        
    }
    
    //判断某个应用是否已收藏
    func isAppFavorite(appId: String,resultClosure:(Bool -> Void)){
        
     
        myQueue?.inDatabase({ (database) in
            
            let sql = "select count(*) as cnt from collect where applicationId = ?"
            
            let rs = database.executeQuery(sql, withArgumentsInArray: [appId])
            
            var cnt:Int32 = 0
            
            if rs.next(){
                
                cnt = rs.intForColumn("cnt")
                
            }
            if cnt > 0{
                
                resultClosure(true)
            }else{
                
                resultClosure(false)
            }
            
            rs.close()
            
        })
    
    }
    //查询数据的方法
    func searchAllCollectData(resultClosure:(Array<CollectModel> -> Void)){
        
        myQueue?.inDatabase({ (database) -> Void in
            
            let sql = "select * from collect"
            
            let rs = database.executeQuery(sql, withArgumentsInArray: nil)
            
           var tmpArray = Array<CollectModel>()
            
            while rs.next(){
                
                let model = CollectModel()
                
                model.collectId = Int(rs.intForColumn("collectId"))
                
                model.applicationId = rs.stringForColumn("applicationId")
                
                model.name = rs.stringForColumn("name")
                
                let data = rs.dataForColumn("headImage")
                
                model.headImage = UIImage(data: data)
                
                tmpArray.append(model)
                
            }
            
            //调用闭包
            resultClosure(tmpArray)
            
            //关闭结果集
            rs.close()
            
        })
        
        
    }

    //删除的方法
    func deleteWithAppId(appId:String,resultClosure:(Bool -> Void)){
        
        myQueue?.inDatabase({ (database) -> Void in
            
            let sql = "delete from collect where applicationId = ?"
            
            let flag = database.executeUpdate(sql, withArgumentsInArray: [appId])

            if flag == false{
                
                print(database.lastErrorMessage())
            }
            
            resultClosure(flag)
        })
        
        
    }
    
    
}
